//
//  ContentView.swift
//  TinyTankDemo
//
//  Created by Mars on 2023/1/15.
//
// UIKit
import SwiftUI
import RealityKit

// Cmd + ,
struct ContentView: View {
  @State var isPlaying = false
  
  var body: some View {
    ZStack {
      ARViewContainer(isPlaying: $isPlaying).edgesIgnoringSafeArea(.all)
      
      // Buttons
      VStack {
        Spacer()
        
        HStack {
          Spacer()
          
          makeButtonsView()
        }
      }
      
    }
  }
  
  func makeButtonsView() -> some View {
    VStack {
      HStack {
        Button(action: {
          if isPlaying {
            return
          }
          else {
            isPlaying = true
            tankAnchor!.notifications.turretLeft.post()
          }
          
        }, label: {
          Image("TurretLeft").resizable().frame(width: 80, height: 80)
        })
        
        Button(action: {
          tankAnchor!.notifications.cannonFire.post()
        }, label: {
          Image("CannonFire").resizable().frame(width: 80, height: 80)
        })
        
        Button(action: {
          tankAnchor!.notifications.turretRight.post()
        }, label: {
          Image("TurretRight").resizable().frame(width: 80, height: 80)
        })
      }
      
      HStack {
        Button(action: {
          tankAnchor!.notifications.tankLeft.post()
        }, label: {
          Image("TankLeft").resizable().frame(width: 80, height: 80)
        })
        
        Button(action: {
          tankAnchor!.notifications.tankForward.post()
        }, label: {
          Image("TankForward").resizable().frame(width: 80, height: 80)
        })
        
        Button(action: {
          tankAnchor!.notifications.tankRight.post()
        }, label: {
          Image("TankRight").resizable().frame(width: 80, height: 80)
        })
      }
    }
  }
}

var tankAnchor: TinyToyTank._TinyToyTank?

// 利用 UIKit 中的相关组件，做一个能显示 AR 模型的 SwiftUI 工具
struct ARViewContainer: UIViewRepresentable {
  @Binding var isPlaying: Bool
  
  func makeUIView(context: Context) -> ARView {
    let arView = ARView(frame: .zero)
    
    // 加载模型文件
    tankAnchor = try! TinyToyTank.load_TinyToyTank()
    tankAnchor?.cannon?.setParent(tankAnchor!.tank, preservingWorldTransform: true)
    tankAnchor?.actions.actionComplete.onAction = { _ in
      self.isPlaying = false
    }
    arView.scene.anchors.append(tankAnchor!)
    
    return arView
  }
  
  func updateUIView(_ uiView: ARView, context: Context) {
    
  }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
  }
}
